package com.li.bottom;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;

/**
 * Author: Li
 * Date: 2017/8/7
 * Description:
 */


public class BottomNavigationView extends LinearLayout
implements View.OnClickListener{
    private int mChildCount;
    private int mSelected=0;
    private int mPreSelected;
    private OnTabSelectedListener mOnTabSelectedListener;
    public BottomNavigationView(Context context) {
        super(context);
    }

    public BottomNavigationView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }


    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        mChildCount=getChildCount();
        if (mChildCount>0) {
            for (int i = 0; i < mChildCount; i++) {
                View view=getChildAt(i);
                if (view instanceof BottomNavigationItem) {
                    BottomNavigationItem item= (BottomNavigationItem) getChildAt(i);
                    item.setTag(i);
                    item.setOnClickListener(this);
                }
            }
        }
    }

    @Override
    public void onClick(View v) {
        mPreSelected=mSelected;
        mSelected= Integer.parseInt(v.getTag().toString());
        if (mOnTabSelectedListener != null) {
            if (mPreSelected==mSelected) {
                mOnTabSelectedListener.onReSelected(mSelected, (BottomNavigationItem) getChildAt(mSelected));
            }else {
                BottomNavigationItem itemSelected=(BottomNavigationItem) getChildAt(mSelected);
                BottomNavigationItem itemUnselected=(BottomNavigationItem) getChildAt(mPreSelected);
                mOnTabSelectedListener.onSelected(mSelected, itemSelected);
                mOnTabSelectedListener.onUnSelected(mPreSelected, itemUnselected);
                itemSelected.setSelected(true);
                itemUnselected.setSelected(false);
            }
        }
    }

    public void setOnTabSelectedListener(OnTabSelectedListener onTabSelectedListener) {
        mOnTabSelectedListener = onTabSelectedListener;
    }

    public interface OnTabSelectedListener{
        void onSelected(int pos, BottomNavigationItem item);
        void onUnSelected(int pos, BottomNavigationItem item);
        void onReSelected(int pos, BottomNavigationItem item);
    }
}
